package com.qmx.launcher;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.open.androidtvwidget.bridge.RecyclerViewBridge;
import com.open.androidtvwidget.leanback.adapter.GeneralAdapter;
import com.open.androidtvwidget.leanback.recycle.LinearLayoutManagerTV;
import com.open.androidtvwidget.leanback.recycle.RecyclerViewTV;
import com.open.androidtvwidget.view.MainUpView;
import com.qmx.launcher.activity.AppCenterActivity;
import com.qmx.launcher.activity.ContactGroupActivity;
import com.qmx.launcher.activity.MiracastActivity;
import com.qmx.launcher.activity.RoomActivity;
import com.qmx.launcher.activity.ScheduleActivity;
import com.qmx.launcher.activity.SettingActivity;
import com.qmx.launcher.activity.FileDialogFragment;
import com.qmx.launcher.activity.base.BaseActivity;
import com.qmx.launcher.adapter.RecyclerViewPresenter;
import com.qmx.launcher.bean.JoinMeeting;
import com.qmx.launcher.bean.LzyResponse;
import com.qmx.launcher.callback.JsonCallback;
import com.qmx.launcher.constant.AppConstant;
import com.qmx.launcher.constant.ComParamContact;
import com.qmx.launcher.token.TokenManager;
import com.qmx.launcher.utils.DateTimeUtils;
import com.qmx.launcher.utils.SocketUtil;
import com.tencent.ilivesdk.core.ILiveLoginManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import io.realm.Realm;

/**
 * recyclerview Demo.
 * setSelectedItemAtCentered 设置一直在中间. (如果设置 false，那么请使用setSelectedItemOffset来设置相差的边距)
 *
 * @author hailongqiu
 */
public class MeetingMainActivity extends BaseActivity implements RecyclerViewTV.OnItemListener, SocketUtil.SocketDataCallback {

    private Context mContext;
    private RecyclerViewTV mRecyclerView;
    private MainUpView mainUpView1;
    private RecyclerViewBridge mRecyclerViewBridge;
    private View oldView;
    private List<String> data = new ArrayList<>();
    private List<Integer> src = new ArrayList<>();
    private TextView show_date;
    //默认选中的位置
    private int mSavePos = 0;
    private RecyclerViewPresenter mRecyclerViewPresenter;
    private GeneralAdapter mGeneralAdapter;
    private Boolean isFirst = true;

    private Realm realm;
    private int roomId;
    private String CLIENT_ID;
    private Gson mGson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recyclerview_activity);
        // 打开debug信息.
        //        OPENLOG.initTag("hailongqiu", true);
        mContext = MeetingMainActivity.this;
        data.add("拨打");
        data.add("通讯录");
        data.add("日程");
        data.add("设置中心");
        src.add(R.drawable.index_1);
        src.add(R.drawable.index_22);
        src.add(R.drawable.index_33);
        src.add(R.drawable.index_44);

        show_date = (TextView) findViewById(R.id.show_date);
        show_date.setText(DateTimeUtils.getNow(DateTimeUtils.FORMAT_SHORT) + "    " + DateTimeUtils.getWeek());

        mRecyclerView = (RecyclerViewTV) findViewById(R.id.recyclerView);
        mainUpView1 = (MainUpView) findViewById(R.id.mainUpView1);
        mainUpView1.setEffectBridge(new RecyclerViewBridge());
        mRecyclerViewBridge = (RecyclerViewBridge) mainUpView1.getEffectBridge();
        recyclerViewLinerLayout(RecyclerView.HORIZONTAL);
        //
        mRecyclerView.setOnItemListener(this);
        // item 单击事件处理.
        mRecyclerView.setOnItemClickListener(new RecyclerViewTV.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerViewTV parent, View itemView, int position) {
                //                Toast.makeText(MeetingMainActivity.this, "点击位置" + position, Toast.LENGTH_SHORT).show();
                enterSelectedActivty(position);
            }
        });

        setTerminalNumber(sharedPreferences.getInt(AppConstant.ROOM_ID, 1234) + "");
        //
        realm = Realm.getDefaultInstance();
        //

        SocketUtil.getInstance();
        SocketUtil.getInstance().setSocketDataCallback(this);
        getClientId();

        checkNet();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    private void getClientId() {
        Log.d("getClientId=", "getClientId: 调用");
        LinkedHashMap<Object, Object> hashMap = new LinkedHashMap<>();
        hashMap.put("token", TokenManager.getInstance().getAuthModel().getToken());
        SocketUtil.getInstance().sendSocketData("auth@login", hashMap);
        hashMap.clear();

    }

    /**
     * 进入选中的activity
     */
    public void enterSelectedActivty(int position) {
        Intent intent = new Intent();
        switch (position) {
            case 0:
                token(realm);
                roomId = sharedPreferences.getInt(AppConstant.ROOM_ID, 1234);
                CLIENT_ID = sharedPreferences.getString(AppConstant.CLIENT_ID, "");
                joinMeeting();
                //                                yunFile();
                return;
            case 1:
                intent.setClass(this, ContactGroupActivity.class);
                break;
            case 2:
                intent.setClass(this, ScheduleActivity.class);
                break;
            case 3:
                intent.setClass(this, AppCenterActivity.class);
                break;
        }
        startActivity(intent);
    }

    public void yunFile() {
        final FileDialogFragment dialog = new FileDialogFragment();
        dialog.show(getSupportFragmentManager(), "FileDialogFragment");

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ILiveLoginManager.getInstance().isLogin()) {
            ILiveLoginManager.getInstance().iLiveLogout();
        }
        if (mNetCheckUtils != null) {
            mNetCheckUtils.unregisterReceiver();
        }
    }

    /**
     * LinerLayout.
     */
    private void recyclerViewLinerLayout(int orientation) {
        LinearLayoutManagerTV layoutManager = new LinearLayoutManagerTV(this);
        layoutManager.setOrientation(orientation);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setFocusable(false);
        mRecyclerViewPresenter = new RecyclerViewPresenter(data, src);
        mGeneralAdapter = new GeneralAdapter(mRecyclerViewPresenter);
        mRecyclerView.setAdapter(mGeneralAdapter);
    }

    @Override
    public void onItemPreSelected(RecyclerViewTV parent, View itemView, int position) {
        //        if (!isListRowPresenter()) {
        mRecyclerViewBridge.setUnFocusView(oldView);
        Log.e("onItemPreSelected", "" + position);
        //        }
    }

    @Override
    public void onItemSelected(RecyclerViewTV parent, final View itemView, final int position) {
        //        if (!isListRowPresenter()) {
        //        System.out.println("onItemSelected===" + position);
        //            mGeneralAdapter.notifyDataSetChanged();
        //        mRecyclerViewBridge.setFocusView(itemView, 1.11f);
        oldView = itemView;
        final ImageView img = (ImageView) itemView.findViewById(R.id.image);
        final ImageView iv_dot = (ImageView) itemView.findViewById(R.id.iv_dot);
        final TextView textView = (TextView) itemView.findViewById(R.id.text_name);
        final LinearLayout ll_bg = (LinearLayout) itemView.findViewById(R.id.ll_bg);
        itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View arg0, boolean isFocused) {
                if (isFocused == true) {
                    selected(position, img, textView, ll_bg, iv_dot);
                } else {
                    unSelected(position, img, textView, ll_bg, iv_dot);
                }
            }
        });
        if (isFirst) {
            int count = parent.getChildCount();
            for (int i = 0; i < count; i++) {
                if (parent.getSelectPostion() == position) {
                    selected(position, img, textView, ll_bg, iv_dot);
                } else {
                    unSelected(position, img, textView, ll_bg, iv_dot);
                }
            }
        }
    }

    private void unSelected(int position, ImageView img, TextView textView, LinearLayout ll_bg, ImageView iv_dot) {
        if (position == 0) {
            img.setImageResource(R.drawable.index_11);
        } else if (position == 1) {
            img.setImageResource(R.drawable.index_22);
        } else if (position == 2) {
            img.setImageResource(R.drawable.index_33);
        } else if (position == 3) {
            img.setImageResource(R.drawable.index_44);
        }
        textView.setTextColor(getResources().getColor(R.color.white));
        iv_dot.setImageResource(R.drawable.index_dot_blue);
        ll_bg.setBackgroundColor(getResources().getColor(R.color.transparent));
    }

    private void selected(int position, ImageView img, TextView textView, LinearLayout ll_bg, ImageView iv_dot) {
        if (position == 0) {
            img.setImageResource(R.drawable.index_1);
        } else if (position == 1) {
            img.setImageResource(R.drawable.index_2);
        } else if (position == 2) {
            img.setImageResource(R.drawable.index_3);
        } else if (position == 3) {
            img.setImageResource(R.drawable.index_4);
        }
        iv_dot.setImageResource(R.drawable.index_dot);
        textView.setTextColor(getResources().getColor(R.color.black));
        ll_bg.setBackgroundResource(R.drawable.index_bg);
    }

    @Override
    public void onReviseFocusFollow(RecyclerViewTV parent, View itemView, int position) {
        //        if (!isListRowPresenter()) {
        //            mRecyclerViewBridge.setFocusView(itemView, 1.11f);
        oldView = itemView;
        Log.e("onReviseFocusFollow", "" + position);
        //        }
    }


    public void joinMeeting() {
        OkGo.<String>post(AppConstant.Url + ComParamContact.Launch.PATH)
                .params(ComParamContact.Launch.TOKEN, TokenManager.getInstance().getAuthModel().getToken())
                .params(ComParamContact.Launch.__TOKEN__, __TOKEN__)
                .params(ComParamContact.Launch.ROOM_ID, roomId)
                .params(ComParamContact.Launch.CLIENT_ID, CLIENT_ID)
                .execute(new JsonCallback<String>() {

                    @Override
                    public void onSuccess(Response<String> response) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String json = jsonObject.optString("code");
                        String msg = jsonObject.optString("msg");
                        Log.i("joinMeeting", json + "");
                        //                        100：平台无此会议号 101：请输入密码 102：密码错误 103：方数不足 104：加入成功 104：短线重连
                        if (json.equals("1")) {
                            Intent intent = new Intent(MeetingMainActivity.this, RoomActivity.class);
                            Log.e("InitiateMeetingActivity", String.valueOf(roomId));
                            intent.putExtra("roomId", roomId);
                            startActivity(intent);
                        } else if (json.equals("0")) {
                            showToast(msg);
                        } else if (json.equals("101")) {
                            showToast("请输入密码");
                        } else if (json.equals("102")) {
                            showToast("密码错误");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.i("onError", response.getException().getMessage());
                    }
                });
    }

    @Override
    public void socketDataCallback(int code, JSONObject str) {
        Log.i("saveClientId", str + "");
        saveClientId(str);
    }
}
